<template>
  <div>
    <el-dialog
      v-el-drag-dialog="{updataFull, updataDialogWidth}"
      :fullscreen="isfullscreen"
      :width="setDialogWidth('800px')"
      :append-to-body="true"
      :visible="visible"
      :title="title"
      @close="close"
      @open="open"
    >
      <el-form
        ref="editform"
        :model="formData"
        label-width="auto"
        :rules="rules"
        class="flex flex-wrap pr-30"
      >
        <el-form-item :label="$t('BELONGS_REGION_NAME')" prop="regionId" class="w-100">
          <el-input v-model="formData.regionId" class="hide" />
          <!-- 区域选择 -->
          <region-cascader
            class="block"
            :selected-ids="[formData.regionId]"
            :clearable="false"
            data-name="onlyRegionTree"
            placeholder="SELECT_REGION"
            :disabled="type === 'view'"
            @change="regionChange"
          />
        </el-form-item>
        <el-form-item :label="$t('FACILITY_NAME')" prop="facilityName" class="w-100">
          <el-input
            v-model="formData.facilityName"
            :placeholder="$t('ENTER_FACILITY_NAME')"
            maxlength="50"
            :readonly="type === 'view'"
          />
        </el-form-item>
        <el-form-item :label="$t('RESOURCE_CODE')" prop="resourceCode" class="w-100">
          <el-input
            v-model="formData.resourceCode"
            :placeholder="`${$t('PLEASE_INPUT')}${$t('RESOURCE_CODE')}`"
            :readonly="type === 'view'"
          />
        </el-form-item>
        <el-form-item :label="$t('FACILITY_TYPE')" prop="facilityType" class="w-100">
          <div class="flex align-center">
            <el-select
              v-model="formData.facilityType"
              :placeholder="`${$t('PLEASE_SELECT')}${$t('FACILITY_TYPE')}`"
              :readonly="type === 'view'"
            >
              <el-option
                v-for="item in dicFacilityTypeList"
                :key="item.code"
                :value="item.code"
                :label="item.name"
              />
            </el-select>
            <span
              v-if="type !== 'view'"
              class="el-icon-edit icon-font ml-5"
              @click="showTypeEdit = true"
            />
          </div>
        </el-form-item>
        <el-form-item :label="$t('GEOGRAPHIC_LOCATION')" class="w-100">
          <div class="flex">
            <el-form-item :label="$t('LONGITUDE')" prop="longitude" class="w-100">
              <el-input v-model="formData.longitude" :readonly="type === 'view'" />
            </el-form-item>
            <el-form-item :label="$t('LATITUDE')" prop="latitude" class="w-100">
              <el-input v-model="formData.latitude" :readonly="type === 'view'" />
            </el-form-item>
            <span
              v-if="type !== 'view'"
              class="el-icon-location-information icon-font ml-5 mt-5"
              @click="showLoacte"
            />
          </div>
        </el-form-item>
      </el-form>

      <template v-slot:footer>
        <el-button @click="close">{{ type === 'view' ? $t('CLOSE') : $t('CANCEL') }}</el-button>
        <el-button v-if="type !== 'view'" type="primary" @click="$debounce(save)">{{
          $t('SAVE')
        }}</el-button>
      </template>
    </el-dialog>
    <!--编辑设施类型-->
    <FacilityType :visible="showTypeEdit" @close="closeType" />
    <!--定位-->
    <locate
      v-if="visible"
      :visible="locateShow"
      :is-mod="type != 'view'"
      :operate-type="type"
      :data="formData"
      @close="locateClose"
    />
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import { changeDecimal } from '@/utils/common'
  import FacilityApi from '@/api/oen/FacilityApi'
  import RegionCascader from '@/components/RegionCascader'
  import FacilityType from './FacilityType'
  import Locate from '../region/Locate'
  export default {
    components: { RegionCascader, FacilityType, Locate },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      type: {
        type: String,
        default: ''
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    inject: ['parentVM'],
    data() {
      return {
        locateShow: false,
        showTypeEdit: false,
        formData: {
          regionId: '',
          facilityName: '',
          facilityType: '',
          resourceCode: '',
          latitude: '',
          longitude: ''
        }
      }
    },
    computed: {
      ...mapGetters(['customDictList']),
      dicFacilityTypeList() {
        const list = this.customDictList.filter(i => i.type === 'FACILITY')
        // 兼容之前未传sort排序
        const arr1 = list.filter(i => !i.update)
        const arr2 = list.filter(i => i.update)
        return [...arr1, ...arr2]
      },
      title() {
        const titleName = {
          view: this.$t('VIEW_FACILITY'),
          add: this.$t('ADDE_FACILITY'),
          mod: this.$t('EDIT_FACILITY')
        }
        return titleName[this.type]
      },
      rules() {
        return {
          regionId: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT_REGION'),
              trigger: 'blur'
            }
          ],
          facilityName: [
            {
              required: true,
              message: this.$t('PLEASE_INPUT') + this.$t('FACILITY_NAME'),
              trigger: 'blur'
            }
          ],
          resourceCode: [
            {
              validator: (rule, value, callback) => {
                const reg = /^[a-zA-Z0-9]+$/
                if (!reg.test(value) && value) {
                  callback(new Error(this.$t('ENCODING_ONLY_NUMBERS_ENGLISH')))
                } else {
                  callback()
                }
              },
              trigger: 'blur'
            }
          ],
          facilityType: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('FACILITY_TYPE'),
              trigger: 'blur'
            }
          ],
          longitude: {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(this.$t('PLEASE_ENTER_LONGITUDE'))
              } else {
                const regLng =
                  /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/
                if (regLng.test(value)) {
                  callback()
                } else {
                  callback(this.$t('LONGITUDE_REG'))
                }
              }
            },
            trigger: ['blur', 'change']
          },
          latitude: {
            required: true,
            validator: (rule, value, callback) => {
              if (!value) {
                callback(this.$t('PLEASE_ENTER_LATITUDE'))
              } else {
                const regLat = /^(\-|\+)?([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/
                if (regLat.test(value)) {
                  callback()
                } else {
                  callback(this.$t('LATITUDE_REG'))
                }
              }
            },
            trigger: ['blur', 'change']
          }
        }
      }
    },
    methods: {
      // 区域搜索条件改变
      regionChange(data) {
        this.formData.regionId = data
      },
      showLoacte() {
        if (!this.formData.longitude && !this.formData.latitude) {
          this.locateShow = true
          return
        }
        const checkArr = []
        this.formData.longitude && checkArr.push('longitude')
        this.formData.latitude && checkArr.push('latitude')
        let locateShow = true
        this.$refs.editform.validateField(checkArr, valid => {
          locateShow = locateShow && !valid
        })
        this.locateShow = locateShow
      },
      locateClose(point) {
        console.log('point', point)
        this.locateShow = false
        if (point && point.longitude && point.latitude) {
          this.formData.longitude = changeDecimal(point.longitude, 6)
          this.formData.latitude = changeDecimal(point.latitude, 6)
        }
      },
      closeType(data) { // 设施类型选择自定义的后 当自定义设施类型删除了 清空设施类型选择
        this.showTypeEdit = false
        if (this.formData.facilityType) {
          const index = data.findIndex(
            i => i.code === this.formData.facilityType
          )
          if (index < 0) {
            this.formData.facilityType = ''
          }
        }
        // 删除设施类型后重新获取列表数据
        this.$parent.loadData && this.$parent.loadData()
      },
      save() {
        this.$refs.editform.validate(valid => {
          if (valid) {
            this.type === 'mod' ? this.updateNode() : this.addNode()
          }
        })
      },
      addNode() {
        FacilityApi.add({ ...this.formData, functionName: this.parentVM.functionName }).then(res => {
          if (res) {
            this.$message.success(this.$t('SAVE_SUCCESS'))
            this.close('load')
          }
        })
      },
      updateNode() {
        FacilityApi.mod({ ...this.formData, functionName: this.parentVM.functionName }).then(res => {
          if (res) {
            this.$message.success(this.$t('SAVE_SUCCESS'))
            this.close('load')
          }
        })
      },
      open() {
        // 判断如果列表设施类型被删除 但code还存在 清空弹窗设施类型值
        if (this.rowData.id) {
          const index = this.dicFacilityTypeList.findIndex(
            i => i.code === this.rowData.facilityType
          )
          if (index < 0) {
            this.rowData.facilityType = ''
          }
        }
        this.$refs.editform && this.$refs.editform.clearValidate()
        this.formData = { ...this.formData, ...this.rowData }
      },
      close(load) {
        this.formData = { ...this.$options.data().formData }
        this.$emit('close', load)
      }
    }
  }
</script>
<style lang="scss" scoped>
  .icon-font {
    font-size: 20px;
    cursor: pointer;
  }
</style>
